
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Workflow.Runtime;
using System.Threading;

namespace T2.Logging.Business
{
    public class WorkflowHelper<W, P>
    {
            public String ValidationErrors { get; set; }
            public Int32 Execute(P param)
            {
                WorkflowRuntime workflowRuntime = new WorkflowRuntime();
                Int32 retVal = -1;
                try
                {
                    

                    AutoResetEvent waitHandle = new AutoResetEvent(false);
                    workflowRuntime.WorkflowCompleted += delegate(object sender,
                    WorkflowCompletedEventArgs e)
                    {
                        retVal = (Int32)e.OutputParameters["RetVal"];
                        if (retVal != 1)
                        {
                            this.ValidationErrors = (string)e.OutputParameters["ValidationErrors"];
                        }
                        waitHandle.Set();
                    };
                    workflowRuntime.WorkflowTerminated += delegate(object sender,
                    WorkflowTerminatedEventArgs e)
                    {
                        retVal = -1;
                        this.ValidationErrors = (string)e.Exception.Message + e.Exception.StackTrace;
                        waitHandle.Set();
                    };
                    Dictionary<string, object> myparams = new Dictionary<string, object>();
                    myparams.Add("Parm", param);
                    WorkflowInstance instance =
                    workflowRuntime.CreateWorkflow(typeof(W), myparams);
                    instance.Start();
                    waitHandle.WaitOne();
                    return retVal;
                }
                catch 
                {
                    throw new ApplicationException(this.ValidationErrors);
                }
                finally
                {
                    if (workflowRuntime != null)
                    {
                        if (workflowRuntime.IsStarted)
                        {
                            workflowRuntime.StopRuntime();
                        }
                        workflowRuntime.Dispose();
                    }
                }
            
            
            }
            
    }
}
